package com.mt.demo.service.impl;

import com.corundumstudio.socketio.SocketIOServer;
import com.mt.demo.manager.MeetingRoomManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
public class GracefulShutdownService {

    @Autowired
    private SocketIOServer socketIOServer;

    @Autowired
    private MeetingRoomManager meetingRoomManager;

    @Autowired(required = false)
    private ScheduledExecutorService scheduledExecutorService;

    @PreDestroy
    public void gracefulShutdown() {
        try {
            // 通知所有客户端服务器即将关闭
            socketIOServer.getAllClients().forEach(client -> {
                client.sendEvent("serverShutdown", "服务器即将关闭，请保存您的工作");
            });

            // 等待2秒让客户端处理关闭通知
            Thread.sleep(2000);

            // 关闭所有客户端连接
            socketIOServer.getAllClients().forEach(client -> {
                try {
                    client.disconnect();
                } catch (Exception e) {
                    // 忽略断开连接时的异常
                }
            });

            // 停止SocketIO服务器
            if (socketIOServer != null) {
                socketIOServer.stop();
            }

            // 关闭定时任务执行器
            if (scheduledExecutorService != null && !scheduledExecutorService.isShutdown()) {
                scheduledExecutorService.shutdown();
                try {
                    if (!scheduledExecutorService.awaitTermination(5, TimeUnit.SECONDS)) {
                        scheduledExecutorService.shutdownNow();
                    }
                } catch (InterruptedException e) {
                    scheduledExecutorService.shutdownNow();
                    Thread.currentThread().interrupt();
                }
            }

            System.out.println("会议系统已优雅关闭");

        } catch (Exception e) {
            System.err.println("优雅关闭过程中出现异常: " + e.getMessage());
        }
    }

    // 处理系统信号
    public void handleShutdownSignal() {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("接收到关闭信号，开始优雅关闭...");
            gracefulShutdown();
        }));
    }
}
